using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Phoenix.Xna.Framework.Properties;

namespace Phoenix.Xna.Framework.Graphics.Animation
{
    public class AnimationChannel : ReadOnlyCollection<AnimationChannelKeyframe>
    {
        internal AnimationChannel(IList<AnimationChannelKeyframe> list)
            : base(list)
        {
        }

        public int GetKeyframeIndexByTime(TimeSpan time)
        {
            if (Count == 0)
            {
                throw new InvalidOperationException(string.Format(Resources.InvalidOperationException, "GetKeyframeIndexByTime", "the channel is empty"));
            }

            int keyframeIndex = 0;
            int startIndex = 0;
            int endIndex = Items.Count - 1;

            while (endIndex >= startIndex)
            {
                keyframeIndex = (startIndex + endIndex) / 2;

                if (Items[keyframeIndex].Time < time)
                {
                    startIndex = keyframeIndex + 1;
                }
                else if (Items[keyframeIndex].Time > time)
                {
                    endIndex = keyframeIndex - 1;
                }
                else
                {
                    break;
                }
            }

            if (Items[keyframeIndex].Time > time)
            {
                keyframeIndex--;
            }

            return keyframeIndex;
        }

        public AnimationChannelKeyframe GetKeyframeByTime(TimeSpan time)
        {
            return Items[GetKeyframeIndexByTime(time)];
        }
    }
}